package com.firewolf.hibernate.mains;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.dto.User;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure();

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}

	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}

	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Test
	public void testSave() {

		openSession();

		User u = new User();
		u.setName("liuxing");
		List<Integer> s = new ArrayList<>();
		s.add(3);
		s.add(1);
		s.add(2);
		u.setScores(s);

		Set<String> ss = new HashSet<>();
		ss.add("篮球");
		ss.add("泡妞");
		ss.add("上网");
		u.setHobbies(ss);

		Map<String, String> map = new HashMap<>();
		map.put("1", "Java");
		map.put("2", "C++");
		u.setCourses(map);

		session.save(u);

		closeSession();
	}
	
	@Test
	public void testQry() {

		openSession();

		User u = (User) session.get(User.class, 1);
		
		System.out.println(u);
		
		closeSession();
	}
}
